<?php
/**
 * @Author: Awe
 * @Date:   2018-05-18 15:30:25
 * @Last Modified by:   Awe
 * @Last Modified time: 2018-06-27 17:36:22
 */
require_once APP_PATH . "/application/library/Qiniu/autoload.php";
// 引入鉴权类
use Qiniu\Auth;
// 引入上传类
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;
class Qiniu_UploadFile{
    protected $accessKey = "";
    protected $secretKey = "";
    protected $bucket = "";
    public function __CONSTRUCT($bucket = "bird" ){
        global $_G ;
        $this->accessKey = $_G['config']['qiniu']['qiniu']['AccessKey'];
        $this->secretKey = $_G['config']['qiniu']['qiniu']['SecretKey'];
        $this->bucket = $bucket ;
    }
    /*public function upload($filePath , $key){
        // 构建鉴权对象
        $auth = new Auth($this->accessKey, $this->secretKey);
        // 生成上传 Token
        $token = $auth->uploadToken($this->bucket);
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return  false ;
        } else {
            return true ;
        }
    }*/
    //获取token
    public function getToken(){
    	// 构建鉴权对象
        $auth = new Auth($this->accessKey, $this->secretKey);
        // 生成上传 Token
        $token = $auth->uploadToken($this->bucket);
        return $token ;
    }
    //根据文件的名称 从七牛获取文件的信息
    /*public  function getFileByFile($filename ){
    	$log = Log_file::getInstance( array('filename' => "qiniu_get_file_log" ) );
		$auth = new Auth($this->accessKey, $this->secretKey);
		//初始化BucketManager
		$bucketMgr = new BucketManager($auth);
		//你要测试的空间， 并且这个key在你空间中存在
		//获取文件的状态信息
		list($ret, $err) = $bucketMgr->stat($this->bucket, $filename);
		if ($err !== null) {
			$log->Write("error",  var_export($err , true ) );
		    return '' ;
		} else {
		    return $ret ;
		}
    }*/
    //刷新资源
    public function refreshResource( $key ){
        $auth = new Auth($this->accessKey, $this->secretKey);
        //初始化BucketManager
        $bucketMgr = new BucketManager($auth);
        $err = $bucketMgr->delete($this->bucket, $key);
        if( !empty($err) or $err !== null ){
            return array('code' => 0 , 'msg' =>$err->message() );
        }
        $err = $bucketMgr->prefetch($this->bucket, $key);
        if( !empty($err) or $err !== null ){
            return array('code' => 0 , 'msg' =>$err->message() );
        }
        return array('code' => 1 ,'msg' => "ok");
    }
}